#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
爬取12306 车次信息
script name: find_train
Created on 2020/3/10 16:05 by PyCharm
@author: fujianjian
"""
import json
from datetime import datetime

import requests


class TrainCrawler:
    __12306_left_ticket_uri__ = 'https://kyfw.12306.cn/otn/leftTicket/query'
    __12306_station_info_uri__ = 'https://www.12306.cn/index/script/core/common/station_name_v10036.js'
    __common_header_param__ = {
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/82.0.4068.5 Safari/537.36',
        'Cookie': 'JSESSIONID=E51B7770F9BD1648BEAEAF617644DC90; _jc_save_wfdc_flag=dc; _jc_save_fromStation=%u5357%u660C%2CNCG; _jc_save_toStation=%u4E0A%u6D77%2CSHH; RAIL_EXPIRATION=1584123235913; RAIL_DEVICEID=DXIJihJRUMeTeYt7eJhIHNqkeGCNYxOfvJnLrJ0myY7iHwZp_x5_reCIr4qWVv1xnLXcRgH6YuYNGcW2CzGomsPdo2vbCsj88xNFtLFkxQuB-POXYycTCctifJKp6HoBBP_2cd3oN8odSD0lIUWAiGHydy0NDCjE; BIGipServerpassport=803733770.50215.0000; route=9036359bb8a8a461c164a04f8f50b252; _jc_save_fromDate=2020-03-11; _jc_save_toDate=2020-03-10; BIGipServerpool_passport=367854090.50215.0000; BIGipServerotn=904921610.50210.0000'

    }
    __save_station_path__ = '/data/code/python/wsite/train_station.json'

    def crawler_ticket_date(self, from_station, to_station, depart_date=datetime.utcnow()):
        """
        查询余票信息
        :param from_station: 始发站
        :param to_station: 终到站
        :param depart_date: 出发日期
        :return:
        """
        param = {
            'leftTicketDTO.train_date': depart_date.strftime('%Y-%m-%d'),
            'leftTicketDTO.from_station': from_station,
            'leftTicketDTO.to_station': to_station,
            'purpose_codes': 'ADULT'
        }
        print('fetch ticket param', param)
        try:

            res = requests.get(self.__12306_left_ticket_uri__, params=param,
                               headers=self.__common_header_param__)
            if res.status_code == 200:
                res_json = res.json()
                code_map = res_json['data']['map']
                train_results = res_json['data']['result']
                result = []
                for line in train_results:
                    temp = line.split('|')
                    if temp[11] == 'Y':
                        train = {
                            # 车次
                            'trainName': temp[3],
                            # 发车时间
                            'departTime': temp[8],
                            # 到达之间
                            'arriveTime': temp[9],
                            # 耗时
                            'spendTime': temp[10],
                            # 无座
                            'wz': temp[29],
                            # 硬座
                            'yz': temp[28],
                            # 硬卧
                            'yw': temp[26],
                            # 软卧
                            'rw': temp[23],
                            # 特等座
                            'td': temp[32],
                            # 一等座
                            'yd': temp[31],
                            # 二等座
                            'ed': temp[30],
                            # 动卧
                            'dw': temp[33]
                        }
                        result.append(train)
                    else:
                        print('车次{}不能购买, {}, {}'.format(temp[3], temp[1], temp[0]))
                with open(r'/data/code/python/wsite/train_info.json', 'w', encoding='utf-8') as wf:
                    json.dump(result, wf, sort_keys=False, ensure_ascii=False, indent=4, separators=(',', ':'))
                    wf.flush()

        except Exception as e:
            print('fetch train ticket info error', e)
        # print('first res', res.json())

        # 获取请求session的写法
        # lts = requests.session()
        # lts.headers = headers
        # print('requests session', lts.headers)
        # lts.verify = False
        # res = lts.get(url)
        # lts.close()
        # res = requests.get(url, verify=False, headers=headers)
        # print('res from 12306', res.text)

        # with open(r'./res.html', 'w', encoding='utf-8') as f:
        #     f.write(res.text)

        pass

    def crawler_station_info(self):
        try:
            res = requests.get(self.__12306_station_info_uri__)
            # print('station info', res.text)
            if res.status_code == 200:
                station_txt = res.text[21:][:-2]
                station_list, count = list(), 0
                for station_line in station_txt.split('@'):
                    temp = station_line.split('|')
                    station = {
                        'pyCode': temp[0],
                        'name': temp[1],
                        'code': temp[2],
                        'pinyin': temp[3],
                        'initial': temp[4],
                        'seq': int(temp[5])
                    }
                    station_list.append(station)
                    count += 1
                    # print('station', station)

                with open(self.__save_station_path__, 'w', encoding='utf-8') as wf:
                    obj = {'code': 200, 'msg': 'success', 'total': count, 'data': station_list}
                    # sort_keys separators indent 格式化相关参数
                    json.dump(obj, wf, sort_keys=True, separators=(',', ':'), indent=4, ensure_ascii=False)
        except:
            print('request station info error!')


if __name__ == '__main__':
    tc = TrainCrawler()

    import datetime as dtp

    depart_date = datetime.utcnow() + dtp.timedelta(days=10)
    # tc.crawler_station_info()

    tc.crawler_ticket_date(from_station='NCG', to_station='SHH', depart_date=depart_date)
